//
//  LFHomeTableViewController.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/19.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit

import SVPullToRefresh

class LFHomeTableViewController: LFBaseViewController {
    
    //MARK: -- 声明一个数组 并在didSet刷新界面
    var status = [LFStatus]() {
        //刷新界面状态
        didSet{
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //如果没有登录，则不设置内容
        if !LFGlobalUserAccountsViewModel.sharedUserAccounts.userLogin {
            return
        }
        //调用方法
        setupTitle()
        setupItemBtn()
        //        statusDataCallBack()
        registerCell()
        pullDownRefresh()
    }
    //MARK: -- 注册cell
    private func registerCell() {
        tableView .registerClass(LFHomeViewCell.self , forCellReuseIdentifier: "ReuseIdentifier")
        
        //自动适应高度 根据cell的高度适应自身高度
//        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
      //MARK: -- tableView高度优化 根据autolayout 去计算高度
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        print("1214")
        let status = self.status[indexPath.row]
        
        if status.rowHight != nil {
            
            return status.rowHight!
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier("ReuseIdentifier") as? LFHomeViewCell
        
        cell?.status = status
        
        let rowHight = cell?.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height
        
        status.rowHight = rowHight
        
        return rowHight!
    }
    
    
    
    //MARK: -- 下拉刷新控件
    private func pullDownRefresh() {
        tableView.LF_refreshingHandlerBlock {[weak self] () -> () in
            //            //模拟
            //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            //                //结束刷新
            //              self?.tableView.LF_endRefreshing()
            //            })
            self?.loadNewStatus()
            
        }
        //切换界面自动开始刷新
        self.tableView.LF_stratRefreshing()
    }
  
    //MARK: -- 请求数据回调
    private func loadNewStatus() {
        //获取since_id
        let  since_id =  status.first?.id ?? 0
        
        LFStatusVM.sharedInstance.loadHomeData(since_id, max_id: 0) { (success, error) -> () in
            
            //网络回调回来就停止刷新
            self.tableView.LF_endRefreshing()
            //判断错误
            if error != nil {
                return
            }
            //判断加载到数据了没
            let count = success?.count ?? 0
            
            //tipLabel
            if since_id > 0 {
                print("下拉刷新count: \(count)")
            self.loadRefreshingLabel(count)
            }
            
            if count == 0 {
                print("没有微博")
                return
            }
            
            //下来刷新
            if since_id > 0 {
                self.status = success! + self.status
            }else { //since_id = 0 不需要刷新
                self.status = success!
                
                //当第一次获取最新数据完成后，再添加上拉加载更多功能
               self.tableView.addInfiniteScrollingWithActionHandler({ () -> Void in
                self.uploadRefreshing()
               })
            }
        }
    }
    
      //MARK: --  上啦刷新
    private func uploadRefreshing() {
        let max_id = status.last?.id ?? 0
        print("\(max_id)");
        
        LFStatusVM.sharedInstance.loadHomeData(0, max_id: max_id) { (success, error) -> () in
            //数据回调成功整天上啦刷新
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil {
                print("获取上啦数据回调出错")
                return
            }
            
            //判断加载到数据了没
            let count = success?.count ?? 0
            
            if count == 0 {
                return
            }
     
            //success 和self.status 顺序固定。 success 在后面
            self.status = self.status + success!
            LFPrint(msg: "上拉加载更多数据: \(success?.count)")
            LFPrint(msg: "最终微博数据条数: \(self.status.count)")
       
        }
    }
   
      //MARK: -- 微博提示label实现
    private func loadRefreshingLabel(count: Int) {
        messageLabel.text = count == 0 ? "没有更新的微博" : "更新了\(count)条微博"
        UIView.animateWithDuration(LFRefreshAnimationTime * 4, animations: { () -> Void in
            self.messageLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateKeyframesWithDuration(LFRefreshAnimationTime * 4, delay: 2, options: UIViewKeyframeAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.messageLabel.frame.origin.y = -64
                    }, completion: nil )
        }
    }
    
    //MARK: -- 懒加载
    //下拉刷新View
    private lazy var refreshView: LFRefreshView = LFRefreshView()
    
    //刷新微博提示label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.whiteColor()
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(16)
        label.frame = CGRect(x: 0, y: -64, width: UIScreen.mainScreen().bounds.width, height: 44)
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
    
    //MARK: -- 设置按钮
    //设置navigationItem.leftItem.right.item
    private func  setupItemBtn() {
        
        //左边Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action:"didClickLeftItem")
        //右边Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action:"didClickRightItem")
    }
    
    //设置navigationItem.title
    func setupTitle() {
        
        let btn = LFTitleBtn(image:"navigationbar_arrow_down", title: "Clemmie")
        navigationItem.titleView = btn
        btn.addTarget(self, action: "didClickTitleBtn:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //MARK : -- 按钮点击事件
    func didClickTitleBtn(btn:LFTitleBtn) {
        
        btn.selected = !btn.selected
        UIView .animateWithDuration(LFRefreshAnimationTime) { () -> Void in
            btn.imageView?.transform = btn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)):CGAffineTransformIdentity
        }
        if btn.selected {
            
            self.setupPopoverView()
        }
    }
    
    //MARK: -- 设置popoverView
    private func setupPopoverView() {
        
        let popoverView = LFPopViewController()
        //设置显示样式
        popoverView.modalPresentationStyle = .Popover
        //设置箭头起始点，在目标view的左上角
        popoverView.popoverPresentationController?.sourceView = navigationItem.titleView
        //设置箭头位置，自动居中指向
        popoverView.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
        //设置代理
        popoverView.popoverPresentationController?.delegate = self
        //设置大小
        popoverView.preferredContentSize = CGSizeMake(200, 44.0 * CGFloat(popoverView.titlesArr.count))
        
        presentViewController(popoverView, animated: true, completion: nil)
    }
    
    //MARK: -- 左右按钮的点击事件
    func didClickLeftItem() {
        
    }
    
    func didClickRightItem() {
        
    }
}

//MARK: -- UITableView数据源和代理
extension LFHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return status.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCellWithIdentifier("ReuseIdentifier", forIndexPath: indexPath) as? LFHomeViewCell
        
        cell?.status = status[indexPath.row]
        
        return cell!
    }
    
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}

//MARK : --UIPopoverPresentationControllerDelegate
extension LFHomeTableViewController:UIPopoverPresentationControllerDelegate {
    
    //不让popover适配iPhone,默认适配.全屏的,不适配就是popover的效果
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    //询问系统是否关闭popover
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        //调用title点击事件,使箭头旋转
        let button = navigationItem.titleView as! LFTitleBtn
        didClickTitleBtn(button)
        
        return true
    }
}
